package com.cn.por.util.tree;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * @author wen
 */
public class TreeNodeUtils {

	private List value;
	
	public TreeNodeUtils() {}
	
	public TreeNodeUtils(List t) {
		this.value = t;
	}
	
	public List getTree(){
		List tree = new ArrayList();
		for(int i=0; i<value.size(); i++) {
			 try {
				Field parent = value.get(i).getClass().getDeclaredField("parentCode");
				parent.setAccessible(true);
				Object parentCode =  parent.get(value.get(i));
				if("43" .equals(parentCode)) {
					tree.add(value.get(i));
					addChilderNode(value.get(i),value);
				 }
			} catch (NoSuchFieldException e) {
				//ignore
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return tree;
	}
	
	private void addChilderNode(Object tree,List listNode) {
		for(int i=0; i< listNode.size(); i++) {
			try {
				Field codeField = tree.getClass().getDeclaredField("code");
				codeField.setAccessible(true);
				Object code = codeField.get(tree);
				
				Field parentField =  listNode.get(i).getClass().getDeclaredField("parentCode");
				parentField.setAccessible(true);
				Object parentCode = parentField.get(listNode.get(i));
				
				if(code.equals(parentCode)) {
					List newNode = new ArrayList();
					newNode.add(listNode.get(i));
					Field field = tree.getClass().getDeclaredField("children");
					field.setAccessible(true);
					field.set(tree, newNode);
					addChilderNode(listNode.get(i),listNode);
				}
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		
		List<MenuNode> a = new ArrayList<MenuNode>();
		MenuNode a1 = new MenuNode();
		a1.setCode("1");
		a1.setName("系统管理");
		a1.setParentCode("");
		a.add(a1);
		MenuNode a2 = new MenuNode();
		a2.setCode("11");
		a2.setParentCode("1");
		a2.setName("用户管理");
		a.add(a2);
		
		TreeNodeUtils tu = new TreeNodeUtils(a);
		ObjectMapper om = new ObjectMapper();
		try {
			System.out.println(om.writeValueAsString(tu.getTree()));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
	}
	
}
